#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
using namespace std;

class Solution {
	vector<int> father;
	int sets = 0;
	int find(int x)
	{
		return father[x] == x ? x : father[x] = find(father[x]);
	}

	void merge(int x, int y)
	{
		int fx = find(x);
		int fy = find(y);
		if (fx != fy) {
			father[fx] = fy;
			sets--;
		}
	}

    public:
	int removeStones(vector<vector<int>> &stones)
	{
		int n = stones.size();
		father.resize(n + 1);
		iota(father.begin(), father.end(), 0);
                sets = n;
		int row, col;
		map<int, int> firstrow;
		map<int, int> firstcol;
		for (int i = 1; i <= n; i++) {
			row = stones[i - 1][0];
			col = stones[i - 1][1];

                        if(firstrow[row]){
                                merge(i, firstrow[row]);
                        }else{
                                firstrow[row] = i;
                        }

                        if(firstcol[col]){
                                merge(i, firstcol[col]);
                        }else{
                                firstcol[col]  = i;
                        }
		}

                return n - sets;
	}
};

int main()
{
	vector<vector<int>> stones = { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 }, { 2, 2 } };
	cout << Solution().removeStones(stones) << endl;
	return 0;
}